package com.wlbx.agent.ui.fragment.tab;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseFragment;
import com.wlbx.agent.bean.InOnlineBean;
import com.wlbx.agent.bean.PartnerBean;
import com.wlbx.agent.bean.ProductSubType;
import com.wlbx.agent.bean.SuitableGroupBean;
import com.wlbx.agent.event.UpdateDrawerLayoutEvent;
import com.wlbx.agent.event.UpdateEditTextEvent;
import com.wlbx.agent.event.UpdateFilterEvent;
import com.wlbx.agent.event.UpdateOnlineLayoutEvent;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.ui.activity.MainActivity;
import com.wlbx.agent.ui.fragment.ProductListFragment;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.view.NoScrollViewPager;
import com.wlbx.agent.view.ScaleTransitionPagerTitleView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 产品列表页面
 */
public class ProductFragment extends BaseFragment {


    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.dl_filter)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.iv_close_menu)
    ImageView ivCloseMenu;
    @BindView(R.id.btn_reset)
    Button btnReset;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.rl_go_to_search)
    RelativeLayout rlGoToSearch;
    @BindView(R.id.tfl_in_online)
    TagFlowLayout tflInOnline;
    @BindView(R.id.tfl_partner)
    TagFlowLayout tflPartner;
    @BindView(R.id.tfl_sub_type)
    TagFlowLayout tflSubType;
    @BindView(R.id.tfl_suitable_group)
    TagFlowLayout tflSuitableGroup;
    @BindView(R.id.tv_keyword)
    TextView tvKeyword;


    @BindView(R.id.tv_sign)
    TextView tvSign;

    @BindView(R.id.iv_filter)
    ImageView ivFilter;





    private List<String> mDataList = new ArrayList<>();
    private List<String> mIndexDataList = new ArrayList<>();
    private List<InOnlineBean.DataDTO> mInOnlineList = new ArrayList<>();
    private List<PartnerBean.DataDTO> mPartnerList = new ArrayList<>();
    private List<ProductSubType.DataDTO> mSubTypeList = new ArrayList<>();
    private List<SuitableGroupBean.DataDTO> mSuitableGroupList = new ArrayList<>();

    @Override
    protected int getInflateViewId() {
        return R.layout.fragment_product;
    }

    @Override
    public void initData() {
        initDrawerLayoutData();
    }



    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        tvKeyword.setText(Constant.PRODUCT_NAME);
        if (!TextUtils.isEmpty(Constant.IS_ONLINE)||!TextUtils.isEmpty(Constant.PARTNER_ID)||!TextUtils.isEmpty(Constant.PRODUCT_SUB_TYPE)){
            tvSign.setTextColor(getActivity().getColor(R.color.colorAccent));
            //TODO
            ivFilter.setBackgroundResource(R.mipmap.icon_filter_check);
        }else {
            tvSign.setTextColor(getActivity().getColor(R.color.colorFontHint));
            ivFilter.setBackgroundResource(R.mipmap.icon_filter);
        }
    }

    public void getInOnline() {
        final Map<String, String> map = new HashMap<>();
        map.put("issueCode","");//出单方式编码
        map.put("issueName","");//出单方式名称
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getInOnline(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                        InOnlineBean bean=JSON.parseObject(response,InOnlineBean.class);
                        mInOnlineList=bean.getData();
                        initIsOnlineList(mInOnlineList);
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }


    TagAdapter onlineAdapter;
    private void initIsOnlineList(List<InOnlineBean.DataDTO>mInOnlineList) {
             onlineAdapter=new TagAdapter<InOnlineBean.DataDTO>(mInOnlineList) {
            @Override
            public View getView(FlowLayout parent, int position, InOnlineBean.DataDTO dto)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_menu_label,
                        tflInOnline, false);
                tv.setText(dto.getIssueName());
                return tv;
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
                Constant.IS_ONLINE="";
            }
        };


        tflInOnline.setAdapter(onlineAdapter);
        tflInOnline.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                Constant.IS_ONLINE="";
                for (Integer s :selectPosSet) {

                    Constant.IS_ONLINE=mInOnlineList.get(s).getIssueCode();
                }
                Logger.i(Constant.IS_ONLINE+"-----");

            }
        });
    }

    public void initDrawerLayoutData() {
        tvKeyword.setText(Constant.PRODUCT_NAME);
        //出单方式
        getInOnline();
        //合作机构
        getPartner();
        //产品类型
        getSubType();
        Constant.IS_ONLINE="";
        Constant.PARTNER_ID ="";
        Constant.PRODUCT_SUB_TYPE="";
    }
    public void getPartner() {
        final Map<String, String> map = new HashMap<>();
        map.put("partnerId","");//机构流水号
        map.put("partnerName","");//机构名称
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getPartner(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i("--v--"+response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                        PartnerBean bean=JSON.parseObject(response,PartnerBean.class);
                        mPartnerList=bean.getData();
                        initPartnerList(mPartnerList);
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }

    private void initPartnerList(List<PartnerBean.DataDTO> mPartnerList) {
        tflPartner.setAdapter(new TagAdapter<PartnerBean.DataDTO>(mPartnerList)
        {
            @Override
            public View getView(FlowLayout parent, int position, PartnerBean.DataDTO dto)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_menu_label,
                        tflPartner, false);
                tv.setText(dto.getPartnerName());
                return tv;
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
                Constant.PARTNER_ID="";
            }

        });

        tflPartner.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                Constant.PARTNER_ID="";
                for (Integer s :selectPosSet) {

                    Constant.PARTNER_ID+=mPartnerList.get(s).getPartnerId()+",";
                }
                Logger.i(Constant.PARTNER_ID+"-----");

            }
        });
    }


    public void getSubType() {
        final Map<String, String> map = new HashMap<>();
        map.put("productSubType","");//产品子类型编码
        map.put("productSubTypeName","");//产品子类型名称
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getSubType(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                        ProductSubType bean=JSON.parseObject(response,ProductSubType.class);
                            mSubTypeList = bean.getData();
                            mSubTypeList.add(0,new ProductSubType.DataDTO("","热销"));
                            for (ProductSubType.DataDTO dataDTO : mSubTypeList) {
                                mDataList.add(dataDTO.getProductSubTypeName());
                                mIndexDataList.add(dataDTO.getProductSubType());
                            }
                            initFragments(mSubTypeList);
                            initSubTypeList(mSubTypeList);

                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }

    private void initSubTypeList(List<ProductSubType.DataDTO> mSubTypeList) {
        tflSubType.setAdapter(new TagAdapter<ProductSubType.DataDTO>(mSubTypeList) {
            @Override
            public View getView(FlowLayout parent, int position, ProductSubType.DataDTO dto) {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_menu_label,
                        tflSubType, false);
                tv.setText(dto.getProductSubTypeName());
                return tv;
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
                Constant.PRODUCT_SUB_TYPE="";
            }
        });
        tflSubType.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                Constant.PRODUCT_SUB_TYPE="";
                for (Integer s :selectPosSet) {

                    Constant.PRODUCT_SUB_TYPE=mSubTypeList.get(s).getProductSubType();
                }
                Logger.i(Constant.PRODUCT_SUB_TYPE+"-----");
            }
        });

    }

    @Override
    public void initEvent() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
//监听
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
//                Logger.i("滑动中");
            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
//                Logger.i("打开");
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
//                Logger.i("关闭");
            }

            @Override
            public void onDrawerStateChanged(int i) {
//                Logger.i("状态改变");
            }
        });
    }

    private void initMagicIndicator() {
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(context);
        commonNavigator.setAdjustMode(false);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override

            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(18);
                simplePagerTitleView.setNormalColor(Color.parseColor("#828282"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#F68657"));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mFragmentContainerHelper.handlePageSelected(index);
                        UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                        updateProductListEvent.setProductSubType(mSubTypeList.get(index).getProductSubType());
                        updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
                        updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                        updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                        EventBus.getDefault().postSticky(updateProductListEvent);
                        switchPages(index);
                    }
                });

                BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);
                badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);
                return badgePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 4));
                indicator.setLineWidth(UIUtil.dip2px(context, 20));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(Color.parseColor("#F68657"));


                return indicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator);
    }

    @OnClick({R.id.ll_filter,R.id.iv_close_menu,R.id.rl_go_to_search,R.id.btn_confirm,R.id.btn_reset})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_filter:
                mDrawerLayout.openDrawer(Gravity.START);
                break;
            case R.id.iv_close_menu:
                mDrawerLayout.closeDrawer(Gravity.START);
                break;
            case R.id.rl_go_to_search:
                IntentUtil.goSearchActivity(getActivity(),"product");

                break;
            case R.id.btn_confirm:
                mDrawerLayout.closeDrawer(Gravity.START);
                mFragmentContainerHelper.handlePageSelected(mIndexDataList.indexOf(Constant.PRODUCT_SUB_TYPE));
                UpdateProductListEvent updateProductListEvent = new UpdateProductListEvent();
                updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
                EventBus.getDefault().postSticky(updateProductListEvent);

                if (!TextUtils.isEmpty(Constant.IS_ONLINE)||!TextUtils.isEmpty(Constant.PARTNER_ID)||!TextUtils.isEmpty(Constant.PRODUCT_SUB_TYPE)){
                    tvSign.setTextColor(getActivity().getColor(R.color.colorAccent));
                    //TODO
                    ivFilter.setBackgroundResource(R.mipmap.icon_filter_check);
                }else {
                    tvSign.setTextColor(getActivity().getColor(R.color.colorFontHint));
                    ivFilter.setBackgroundResource(R.mipmap.icon_filter);
                }

                break;
            case R.id.btn_reset:
                initDrawerData();
                break;
            default:
                break;
        }
    }

    private void initDrawerData() {
        initIsOnlineList(mInOnlineList);
        Constant.IS_ONLINE="";
        initSubTypeList(mSubTypeList);
        Constant.PRODUCT_SUB_TYPE="";
        initPartnerList(mPartnerList);
        Constant.PARTNER_ID ="";

    }


    public static ProductFragment getInstance(){
        return new ProductFragment();
    }

    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
    private void initFragments(List<ProductSubType.DataDTO> mSubTypeList ) {
        for (int i = 0; i < mSubTypeList.size(); i++) {
            ProductListFragment productListFragment = new ProductListFragment();
                mFragments.add(productListFragment);

        }
        initMagicIndicator();
        mFragmentContainerHelper.handlePageSelected(0, false);
        switchPages(0);
    }
    private void switchPages(int index) {
        FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment;
        for (int i = 0, j = mFragments.size(); i < j; i++) {
            if (i == index) {
                continue;
            }
            fragment = mFragments.get(i);
            if (fragment.isAdded()) {
                fragmentTransaction.hide(fragment);
            }
        }
        fragment = mFragments.get(index);
        if (fragment.isAdded()) {
            fragmentTransaction.hide(fragment).show(fragment);
        } else {
            fragmentTransaction.add(R.id.fragment_container, fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void refreshLayout(UpdateOnlineLayoutEvent updateOnlineLayoutEvent) {
        Constant.IS_ONLINE = updateOnlineLayoutEvent.getIsOnline();
        Logger.i("出单方式---"+Constant.IS_ONLINE);
        if (Constant.IS_ONLINE.equals("Y")){
            onlineAdapter.setSelectedList(1);
        }else if (Constant.IS_ONLINE.equals("N")){
            onlineAdapter.setSelectedList(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void refreshFilter(UpdateFilterEvent updateFilterEvent) {
        if (!TextUtils.isEmpty(Constant.IS_ONLINE)||!TextUtils.isEmpty(Constant.PARTNER_ID)||!TextUtils.isEmpty(Constant.PRODUCT_SUB_TYPE)){
            tvSign.setTextColor(getActivity().getColor(R.color.colorAccent));
            //TODO
            ivFilter.setBackgroundResource(R.mipmap.icon_filter_check);
        }else {
            tvSign.setTextColor(getActivity().getColor(R.color.colorFontHint));
            ivFilter.setBackgroundResource(R.mipmap.icon_filter);
        }


    }

}
